// Array utils
if(!Array.prototype.last) 
{
	Array.prototype.last = function() {
		return this[this.length - 1];
	}
}

if(!Array.prototype.first) 
{
	Array.prototype.first = function() {
		return this[0];
	}
}

// ui
function show_progress(value)
{
	// alert("progress: " + value)
	$( "#progressbar" ).progressbar({
		value: value
	})
}

function show_add_result(video_id, result)
{	
	x = result ? "#OK":  "#FAIL";
	$( x + video_id ).each( function(index, element) {
		$(this).css("display", "block");
	})
}

function show_add_fail(video_id) {
	show_add_result(video_id, false);
}

function show_add_ok(video_id) {
	show_add_result(video_id, true);
}

function calculate_video_progress(videos)
{
	steps_left  = videos.length;
	steps_total = CURRENT_VIDEOS.length;
	steps_taken = steps_total - steps_left;
	step_length = 100 / steps_total;
	progress = steps_taken * step_length;
	
	// alert( "L" + steps_left + "T" + steps_total + "t" + steps_taken + "L" + step_length + "P" + progress );
	
	return progress
}
// recursively send one add_request per second
function add_videos_to_playlist(list_id, videos, new_list, EndCallback)
{
	video_id = videos.shift();
	url = "/add?list=" + encodeURIComponent(list_id) + "&vid=" + encodeURIComponent(video_id);
	
	// alert("add_videos_to_playlist: url=" + url);
	$.ajax({
		url: url
	}).success( function(response) { 
		// alert("add_videos_to_playlist: success");
		
		toggle_header();
		show_progress( calculate_video_progress(videos) );
		
		if ( response == 1 )
		{
			// alert("add_videos_to_playlist: good response");
			show_add_ok(video_id);
		}
		else
		{
			// alert("add_videos_to_playlist: bad response");
			show_add_fail(video_id);
		}

		
		if (videos.length > 0)
		{
			// alert("add_videos_to_playlist: videos left");
			window.setTimeout(function() {
				add_videos_to_playlist(list_id, videos, new_list, EndCallback)
			}, 500);
		}
		else
		{
			// alert("add_videos_to_playlist: end");
			show_progress(100);
			if (EndCallback)
				EndCallback();
		}

	}).error(function(e, xhr) { 
		// alert('alert("add_videos_to_playlist: error (' + url + ')' );
		show_add_fail(video_id);
		
	})
}

function add_playlist ( new_list, name, success, error )
{
	url = "/list?list=" + encodeURIComponent(CURRENT_PLAYLIST_ID);
	
	if ( new_list )
		url = url + "&new=1"
		
	if ( name )
		url = url + "&name=" + encodeURIComponent(name) 
	
	// alert("add_playlist: url = " + url);
	
	$.ajax({
		url: url
	}).success(function(data) { 
		// alert("add_playlist: sucess = " + data);
		list_id = data;
		if ( success )
			success(list_id)
	}).error(function(e, xhr) { 
		// alert("add_playlist: error (" + url + ")");
		if ( error )
			error(e, xhr)
	});
}

function current_video_ids()
{
	var videos = [];
	// alert("current_video_ids");
	
	$(".video").each(function(index){ 
		// alert("current_video_ids: each");
		href = $(this).attr("href");
		if ( match = href.match( /v=([a-z0-9_-]+)/i ) )
		{
			// alert("current_video_ids: match = " + match[1]);
			videos.push ( match[1] ); 
		}
	});
	
	return videos;
}

function toggle_header()
{
	// alert("toggle_header");
	$( "#header_menu" ).css("display", "none");
	$( "#header_progressbar" ).css("display", "inline");
}

function save_videos (new_list, name)
{
	// alert("save_videos + (" + new_list + ", " + name + ")");
	add_playlist ( new_list, name,
		// success
		function(list_id) { 
			// alert("save_videos: success");
			if ( list_id )
			{
				// alert("save_videos: true list_id");
				var videos     = current_video_ids();
				// alert("save_videos: videos found = " + videos.length);
				var last_vid   = videos.first();
				// alert("save_videos: last video id = " + last_vid);
				var ytredirect = function () {
					window.location = "http://www.youtube.com/watch?v=" + last_vid + "&list=" + list_id
				}
				// alert("save_videos: adding videos");
				add_videos_to_playlist(list_id, videos, new_list, ytredirect);
			}
			else
			{
				alert("save_videos: Could not receive playlist id")
			}
		}, 
		// error
		function(e, xhr	) { 
			alert('save_videos: error in save_videos (' + newlist + ", " + name  + ')');
		}
	);
}

function reverse_playlist()
{
	var l = document.getElementById("sortable");
	var i  = l.childNodes.length;
	while (i--)
		l.appendChild( l.childNodes[i] );
}

$(document).ready(function() {
	// reverse videos
	$("#reverse_playlist").click( function() { reverse_playlist(); return false });
	// add videos to view later
	$("#add_to_watch_later").click(  function() { save_videos(false, null); return false });
	// new list with name
	$("#add_to_new_playlist").click( function() { 
		$("#plname").val(CURRENT_PLAYLIST_NAME + " - Reordered");
		
		dialog_ok = function (self)
		{
			name = $("#plname").val();

			if ( name )
				save_videos(true, name); 

			$( self ).dialog( "close" );
			return false 
		}
		
		dialog_cancel = function (self)
		{
			$( self ).dialog( "close" );
			return false 
		}

		dialog = $("#dialog-confirm" ).dialog({
			resizable: false,
			height:133,
			width: 290,
			modal: true,
			buttons: { 
				"Cancel": function() { return dialog_cancel(this) },
				"OK":     function() { return dialog_ok(this) }
			}
		});
		
		$("#plname").keypress(function(event) {
			if ( event.which == 13 ) 
				dialog_ok(dialog);
		});
	});
	
	$(function() {
		$( "#sortable" ).sortable();
		$( "#sortable" ).disableSelection();
	});
	
	$(function() {
		$( "#reverse_playlist, #add_to_new_playlist, #add_to_watch_later" )
		.button()
		.click(function( event ) {
			event.preventDefault();
		})
	});
	
	$("#list_title").click( function() { 
		$( "#desc_overlay" ).dialog({
			width: 600,
			modal: true,
		});
	});
});
